<template>
  <el-header class="app-header">
    <div class="header-container">
      <div class="header-title">
        <img src="../assets/images/logo.png" alt="WIN-WIN" class="logo-image" />
        <h1>{{ title }}</h1>
      </div>

      <!-- 新增导航菜单 -->
      <div class="nav-menu">
        <el-button type="text" @click="navigateTo('/')">返回主页</el-button>
        <el-button type="text" @click="navigateTo('/dashboard')">浏览职位</el-button>
        <el-button type="text" @click="navigateTo('/jobs')">浏览人才</el-button>
        <el-button type="text" @click="navigateTo('/meet')">论坛交流</el-button>
        <el-button type="text" @click="navigateTo('/resources')">求职指南</el-button>
        <el-button type="text" @click="navigateTo('/message')">查看消息</el-button>
      </div>

      <div class="user-area">
        <div v-if="!auth.isLoggedIn" class="auth-buttons">
          <el-button type="text" @click="navigateTo('/login')">登录</el-button>
          <el-button type="text" @click="navigateTo('/register')">注册</el-button>
        </div>

        <div v-else class="user-center">
          <el-dropdown @command="handleCommand" trigger="click">
            <div class="user-dropdown">
              <el-avatar :size="32" icon="el-icon-user" class="user-avatar">
                <User/>
              </el-avatar>
              <span class="el-dropdown-link">
                个人中心<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><user-filled /></el-icon> 我的资料
                </el-dropdown-item>
                <el-dropdown-item command="message">
                  <el-icon><Notebook /></el-icon> 我的消息
                </el-dropdown-item>
                <el-dropdown-item command="info">
                  <el-icon><document /></el-icon>
                  {{ auth.role === 'job_seeker' ? '求职信息' : '招聘信息' }}
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><switch-button /></el-icon> 退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
  </el-header>
</template>

<script setup>
import { onMounted, watch, ref, onBeforeUnmount } from 'vue'
import { ArrowDown, User, UserFilled, Document, SwitchButton, Notebook } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../store/auth.js'

const props = defineProps({
  title: {
    type: String,
    default: '双赢'
  }
})

const router = useRouter()
const route = useRoute()
const auth = useAuthStore()

// 监听登录状态变化
watch(() => auth.isLoggedIn, (newVal) => {
  if (newVal) {
    fetchUserInfo()
  } else {
    // 登出时处理
    checkAuthState()
  }
})

// 监听用户登出全局事件
const handleUserLogout = () => {
  console.log('Header 组件接收到用户登出事件')
  // 确保导航区域能够正确响应登出状态
  checkAuthState()
}

// 检查当前登录状态并处理受保护路由
const checkAuthState = () => {
  if (!auth.isLoggedIn) {
    // 如果在需要登录的页面，则重定向到登录页
    const protectedRoutes = ['/profile', '/seek', '/recruit', '/dashboard','/message']
    if (protectedRoutes.includes(route.path)) {
      router.push('/login')
      ElMessage.warning('请先登录以访问该页面')
    }
  }
}

const navigateTo = (path) => {
  router.push(path)
}

const handleCommand = (command) => {
  switch(command) {
    case 'profile':
      navigateTo('/profile')
      break
    case 'message':
      navigateTo('/message')
      break
    case 'info':
      navigateTo( auth.role === 'job_seeker' ? '/seek' : '/recruit')
      break
    case 'logout':
      logout()
      break
  }
}

const fetchUserInfo = async () => {
  try {
    const userId = auth.userId || localStorage.getItem('user_id');
    if (!userId) {
      console.error('未找到用户ID');
      auth.logout();
      return;
    }

    const token = auth.token || localStorage.getItem('token');
    if (!token) {
      console.error('未找到用户token');
      auth.logout();
      return;
    }

    // 使用完整URL并添加Authorization头
    const response = await fetch(`http://127.0.0.1:8000/api/user-info?user_id=${userId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      }
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`获取用户信息失败：${errorText}`);
    }

    const userInfo = await response.json();
    console.log('用户信息:', userInfo); // 调试用
    return userInfo; // 返回用户信息供后续使用
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 不要自动登出，避免循环重定向
    // auth.logout();
  }
}

const logout = async () => {
  try {
    auth.logout()
    ElMessage.success('退出成功')
    navigateTo('/login')
  } catch (error) {
    ElMessage.error('退出失败')
  }
}

onMounted(() => {
  // 检查是否登录并获取用户信息
  if (auth.isLoggedIn) {
    fetchUserInfo()
  }

  // 添加登出事件监听
  window.addEventListener('user-logout', handleUserLogout)

  // 页面加载时检查登录状态
  checkAuthState()
})

onBeforeUnmount(() => {
  // 移除事件监听器，避免内存泄漏
  window.removeEventListener('user-logout', handleUserLogout)
})
</script>

<style scoped>
.app-header {
  background: url('/p2.jpg') center/cover no-repeat;
  color: white;
  line-height: 60px;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1000;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 100%;
}

.header-title {
  display: flex;
  align-items: center;
}

.logo-image {
  width: 36px;
  height: 36px;
  margin-right: 10px;
}

.header-title h1 {
  margin: 0;
  font-size: 22px;
  letter-spacing: 1px;
  font-weight: 600;
}

/* 新增导航菜单样式 */
.nav-menu {
  display: flex;
  align-items: center;
  margin-left: 40px;
  flex-grow: 1;
}

.nav-menu .el-button {
  color: white;
  margin: 0 10px;
  font-size: 16px;
  transition: all 0.3s;
}

.nav-menu .el-button:hover {
  transform: translateY(-2px);
  text-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.user-area {
  display: flex;
  align-items: center;
  height: 100%;
}

.auth-buttons .el-button {
  color: white;
  margin-left: 15px;
  font-size: 16px;
  transition: all 0.3s;
}

.auth-buttons .el-button:hover {
  transform: translateY(-2px);
  text-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.user-center {
  height: 100%;
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 15px;
  height: 60px;
  transition: all 0.3s;
}

.user-dropdown:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-avatar {
  margin-right: 8px;
  background-color: #fff;
  color: #409EFF;
}

.el-dropdown-link {
  color: white;
  display: flex;
  align-items: center;
  font-size: 16px;
}

.el-icon--right {
  margin-left: 5px;
  font-size: 12px;
}

/* 下拉菜单项样式 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  line-height: 36px;
}

:deep(.el-dropdown-menu__item i) {
  margin-right: 5px;
  font-size: 16px;
}
</style>